package com.asiainfo.iam.service;


import com.asiainfo.iam.config.ResMsg;
import com.asiainfo.iam.config.Result;
import com.asiainfo.iam.constant.AuthConstant;
import com.asiainfo.iam.entity.dto.SessionIdentity;
import com.asiainfo.iam.entity.vo.LoginResultVo;
import com.asiainfo.iam.entity.vo.UserInfoVo;
import com.asiainfo.iam.mapper.UserIdentityMapper;
import com.hangmu.iam.sdk.client.AisDataSyncAppClient;
import com.hangmu.iam.sdk.client.AisSSoClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Service
public class SsoService {
    private static final Logger log  = LoggerFactory.getLogger(SsoService.class);

    @Autowired
    private UserIdentityMapper userIdentityMapper;

    /**
     * 门户单点登录
     * @param code 用户凭证code（用户登录后获取的临时凭证）
     * @return 登录结果
     */
    public Result portalLogin(String code, HttpServletRequest request){
        try {
            // 调用SDK的登录方法
            com.hangmu.iam.sdk.util.ResMsg result = AisSSoClient.login(code);
            // 封装返回结果
            ResMsg<LoginResultVo> tokenMsg = new ResMsg<>();
            tokenMsg.setCode(result.getCode());
            tokenMsg.setMsg(result.getMsg());

            if (AuthConstant.SUCCESS.equals(result.getCode())){
                tokenMsg.setData((LoginResultVo) result.getData());
                //拿到token
                String webToken = tokenMsg.getData().getWebToken();
                log.info("获取到webToken: {}", webToken);
                //拿到token来调用sdk获取用户信息
                com.hangmu.iam.sdk.util.ResMsg userInfo = AisDataSyncAppClient.getUserInfo(webToken);
                // 封装返回结果
                ResMsg<UserInfoVo> userInfoMsg = new ResMsg<>();
                userInfoMsg.setCode(result.getCode());
                userInfoMsg.setMsg(result.getMsg());
                if(AuthConstant.SUCCESS.equals(userInfo.getCode())){
                    //把信息放入session
                    //1.获取用户信息中的用户id--account
                    userInfoMsg.setData((UserInfoVo) userInfo.getData());
                    String userId = ((UserInfoVo) userInfo.getData()).getAccount();
                    //2.根据id查数据库中的一些字段
                    SessionIdentity sessionIdentity =userIdentityMapper.getSessionIdentity(userId);
                    if(sessionIdentity != null){
                        log.info("sessionIdentity: {}", sessionIdentity);
                        //3.把sessionIdentity放入session
                        HttpSession session = request.getSession();
                        session.setAttribute("sessionIdentity",sessionIdentity);
                        return Result.success("登录成功");
                    }else {
                        return Result.error("登录失败");
                    }
                }else {
                    log.info("根据token获取用户信息失败！");
                    return Result.error(userInfo.getMsg(), userInfo.getCode());
                }

            }else{
                log.info("获取token失败！");
                return Result.error(result.getMsg(), result.getCode());
            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }


}
